<!-- 登录页面 -->
<script setup lang="ts">
import { ElMessage, FormInstance } from 'element-plus';
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import ROUTER_CONSTANTS from '../route/constants';
import { authenticateUser, authorizeUser } from '../services/user';
import useStore from '../store/modules/User';

// 全局路由
const router = useRouter();
// User store
const userStore = useStore();
// 登录表单引用
const ruleFormRef = ref<FormInstance>();
// 登录表单接口
interface LoginForm {
  username: string;
  password: string;
}

const param = reactive<LoginForm>({
  username: 'admin',
  password: '123123',
});

// 表单验证
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 首先发送用户名和密码给后台，进行authenticate操作
      const authenticateResponse = await authenticateUser(
        param.username,
        param.password
      );
      if (authenticateResponse.status === 200) {
        // 如果authenticate成功，使用返回的token继续执行authorize操作
        const authResponse = await authorizeUser(
          authenticateResponse.data.token
        );
        // 如果authorize成功，则将返回的用户信息保存到User store中，并跳转
        if (authResponse.status === 200) {
          const userInfo = authResponse.data;
          // 保存用户信息
          userStore.setUser(userInfo);
          ElMessage.success('登录成功');
          // 默认跳转到首页
          router.replace({
            name: ROUTER_CONSTANTS.JOBLIST,
          });
        }
      } else {
        // 将接口返回的错误信息赋值给errorMessage响应式变量
        ElMessage.error('登录发生错误');
      }
    } else {
      ElMessage.error('请仔细检查表单');
    }
  });
};
// 第一次进入页面，判断用户是否已经登录，如果登录则跳转到首页
onMounted(() => {
  if (userStore.isLogin()) {
    router.replace({
      name: ROUTER_CONSTANTS.JOBLIST,
    });
  }
});
</script>

<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">PeekpaJob 管理系统</div>
      <el-form
        ref="ruleFormRef"
        :model="param"
        :rules="rules"
        label-width="0px"
        size="large"
        class="ms-content"
      >
        <el-form-item prop="username">
          <el-input v-model="param.username">
            <template #prepend>
              <el-icon>
                <eli-user />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="param.password"
            type="password"
            placeholder="password"
            size="large"
            @keyup.enter="submitForm(ruleFormRef)"
          >
            <template #prepend>
              <el-icon>
                <eli-lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <div class="login-btn">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >登录</el-button
          >
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background: #324157;
  background-image: url(../assets/login-bg.jpg);
  background-size: 100%;
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
  font-family: HyliaSerif;
}
.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}
</style>
